<template>
  <div>
    <!-- <input v-model="markerName" placeholder="请输入标点的名称" />
    <button @click="toggleMarkerMode">
      {{ addingMarker ? '取消标点' : '开始标点' }}
    </button> -->
    <!-- <button v-if="markers.length > 0" @click="clearMarkers">
      清除所有标点
    </button> -->
    <div class="searchBox" v-if="isShowSearch">
      <el-input
        class="searchItem"
        v-model="searchKeyword"
        placeholder="请输入搜索关键词"
        clearable
        @change="handelChangePoint"
      />
      <el-select
        class="searchItem"
        v-model="pointKey"
        placeholder="请输入搜索关键词后选择"
        filterable
        clearable
        @change="handelChangePoint"
      >
        <el-option
          v-for="item in options"
          :key="item.uid"
          :label="item.title"
          :value="item.title"
        >
        </el-option>
      </el-select>
    </div>
    <div ref="mapContainer" style="width: 100%; height: 500px"></div>
  </div>
</template>

<script>
export default {
  props: {
    isShowSearch: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    isOnePoint: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    closeClick: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
  },
  data() {
    return {
      pointKey: "",
      searchKeyword: "",
      mapInstance: null, // 地图实例
      markerName: "", // 标点名称
      markers: [],
      options: [],
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      // 初始化地图
      const map = new BMap.Map(this.$refs.mapContainer);
      // 设置为卫星地图
      map.setMapType(BMAP_SATELLITE_MAP);
      const point = new BMap.Point(120.09451660916, 30.898963937294); // 湖州的经纬度
      map.centerAndZoom(point, 17);
      map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放
      this.mapInstance = map;
      if (this.closeClick) {
        // 添加地图点击事件监听
        map.addEventListener("click", (e) => {
          this.addMarker(e.point);
        });
      }
      // 初始化本地搜索
      this.localSearch = new BMap.LocalSearch(map, {
        renderOptions: { map: map, panel: "search_results" },
        onSearchComplete: this.onSearchComplete.bind(this),
      });
    },
    searchMap() {
      this.localSearch.search(this.searchKeyword);
    },
    handelChangePoint(e) {
      this.searchKeyword = e;
      this.searchMap();
    },
    flyToLocation(longitude, latitude) {
      if (!this.isValidCoordinate(longitude, latitude)) {
        console.error("无效的经纬度");
        return;
      }

      const targetPoint = new BMap.Point(longitude, latitude);
      this.mapInstance.panTo(targetPoint); // 平滑移动到指定点
    },
    onSearchComplete(results) {
      // 处理搜索结果（可选）
      console.log(results);
      let ponitList = results.Wr || [];
      let uniqueIds = {};
      let uniqueArray = ponitList.filter((item) => {
        const isDuplicate = uniqueIds.hasOwnProperty(item.title);
        uniqueIds[item.title] = true;
        return !isDuplicate;
      });
      console.log(uniqueArray);
      // 这里你可以清除之前的标记点，然后添加新的标记点
      // 但由于我们使用了 LocalSearch 的自动渲染选项，它会自动在地图上显示结果
      this.options = uniqueArray;
    },
    toggleMarkerMode(markerName, point = []) {
      this.markerName = markerName;
      this.$refs.mapContainer.style.cursor = "crosshair";
      if (point.length == 2 && this.isValidCoordinate(point[0], point[1])) {
        let pointList = new BMap.Point(point[0], point[1]);
        this.addMarker(pointList, this.markerName);
        this.markerName = "";
        this.mapInstance.panTo(pointList); // 平滑移动到指定点
      }
    },
    addMarkerList(list) {
      this.clearMarkers();
      list.forEach((item) => {
        let point = item.point;
        let pointList = new BMap.Point(point[0], point[1]);
        this.addMarker(pointList, item.markerName, false);
      });
      if (list.length > 0) {
        let point = list[list.length - 1].point;
        let pointList = new BMap.Point(point[0], point[1]);
        this.mapInstance.panTo(pointList); // 平滑移动到指定点
      }
    },
    addMarker(point, markerName, isClearMarkers = true) {
      console.log(isClearMarkers);
      // if(isClearMarkers){
      //   this.clearMarkers();
      // }
      // 添加标记点
      const marker = new BMap.Marker(point);

      if (this.isOnePoint) {
        this.markers.forEach((marker) => {
          this.mapInstance.removeOverlay(marker); // 从地图中移除标记点
        });
        this.markers=[]
        this.markers = [marker];
      } else {
        this.markers.push(marker); // 将新创建的标记点添加到数组中
      }
      this.mapInstance.addOverlay(marker);
      console.log(
        marker,
        this.markers,
        "this.markersthis.markers",
        this.isOnePoint
      );
      // 创建并添加标签显示名称和坐标信息
      const labelContent = `  
        <div style="color: #fff; background-color: #333; padding: 4px;">  
          ${markerName ? markerName + "<br/>" : ""}  
          经度：${point.lng}<br/>  
          纬度：${point.lat}  
        </div>  
      `;
      const label = new BMap.Label(labelContent, {
        offset: new BMap.Size(20, 20), // 设置标签偏移量
      });
      label.setStyle({
        borderColor: "#333",
        borderWidth: "1px",
        borderRadius: "4px",
        background: "#333",
        padding: "4px",
      });
      marker.setLabel(label);

      // 标记点添加完成后，清空名称输入框

      // 禁用标点模式
      this.toggleMarkerMode();
      this.$emit("getMarker", point);
    },
    clearMarkers() {
      // 清除所有标记点
      this.markers.forEach((marker) => {
        this.mapInstance.removeOverlay(marker); // 从地图中移除标记点
      });
      this.markers = []; // 清空标记点数组
    },
    isValidCoordinate(lon, lat) {
      lon = Number(lon);
      lat = Number(lat);
      // 检查纬度是否在-90到90之间（包含-90和90）
      if (lat < -90 || lat > 90) {
        return false;
      }
      // 检查经度是否在-180到180之间（包含-180和180）
      if (lon < -180 || lon > 180) {
        return false;
      }
      if (
        lat == undefined ||
        lat == "" ||
        lat == null ||
        lon == undefined ||
        lon == "" ||
        lon == null
      ) {
        return false;
      }

      // 如果都通过检查，则可能是有效的经纬度
      return true;
    },
  },
};
</script>

<style lang="scss" scoped>
/* 尝试隐藏百度地图的logo和底部信息 */
::v-deep .BMap_cpyCtrl,
::v-deep .anchorBL {
  display: none !important;
}

.searchBox {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 10px;

  .searchItem {
    width: 300px;
  }
}
</style>